package com.epoint.netty.chat.handler;

import com.epoint.netty.chat.message.ChatResponseMessage;
import com.epoint.netty.chat.message.GroupChatRequestMessage;
import com.epoint.netty.chat.message.GroupCreateRequestMessage;
import com.epoint.netty.chat.message.GroupCreateResponseMessage;
import com.epoint.netty.chat.server.session.Group;
import com.epoint.netty.chat.server.session.GroupSession;
import com.epoint.netty.chat.server.session.GroupSessionFactory;
import com.epoint.netty.chat.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

public class GroupChatRequestHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupChatRequestMessage groupChatRequestMessage) throws Exception {
        String groupName = groupChatRequestMessage.getGroupName();
        String content = groupChatRequestMessage.getContent();

        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Set<String> members = groupSession.getMembers(groupName);

        for (String member : members) {
            Channel channel = SessionFactory.getSession().getChannel(member);

            ChatResponseMessage chatResponseMessage = new ChatResponseMessage(groupName, content);
            channel.writeAndFlush(chatResponseMessage);
        }

    }
}
